/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有，侵权必究！
 */

package com.ruoyi.web.controller.app;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.CommonUtils;
import com.ruoyi.common.utils.RequestUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.tencentUtils.TencentCloudImUtil;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * APP登录授权
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestController
@RequestMapping("/app")
@Api("APP登录接口")
public class ForAppLoginController extends BaseController {

    @Value("${token.expireTime}")
    private int expireTime;
    protected static final long MILLIS_SECOND = 1000;

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;
    @Autowired
    private TencentCloudImUtil tencentCloudImUtil;

    @Autowired
    private SysLoginService loginService;
    @Autowired
    private IAppUserService userService;
    @Autowired
    private IAppUserEquipmentService iAppUserEquipmentService;
    @Autowired
    private IBaseInvitationCodeService iBaseInvitationCodeService;
    @Autowired
    private IAppGroupInfoService iAppGroupInfoService;
    @Autowired
    private IBaseFriendsDefaultService baseFriendsDefaultService;
    @Autowired
    private IAppFunctionConfigurationService appFunctionConfigurationService;
    @Autowired
    private IBaseBlacklistIpsService iBaseBlacklistIpsService;

    @PostMapping("userRegistOrLogin")
    @ApiOperation("根据手机号码，判断用户是否存在")
    public AjaxResult userRegistOrLogin(@ApiParam("手机号码") String phone) {
        // 查询用户是否存在
        AppUser userEntity = userService.getOneByMobile(phone);
        if (null == userEntity) {
            return AjaxResult.error(9999, "未注册");
        } else if (userEntity.getState() == 2) {
            // 用户已存在且账号被删除的情况下，修改账号状态，解禁云信账户
            return AjaxResult.error(-1, "账号注销");
        } else {
            // 登录
            return AjaxResult.ok(0, "", "");
        }
    }

    @PostMapping("v1/userRegist")
    @ApiOperation("用户注册")
    public AjaxResult registInVersion1(@ApiParam("手机号码") @RequestParam String phone, @ApiParam("密码（需要MD5）") @RequestParam String password, @ApiParam("用户昵称") @RequestParam String username, @ApiParam("格式为：设备id,设备名称") String equipmentId, @ApiParam("邀请码") @RequestParam String invitationCode, @ApiParam("头像") @RequestParam String headUrl, HttpServletRequest request) {
        String lastIp = RequestUtil.getIpAddrByRequest(request);
        // 判断是否为黑名单数据
        Boolean isTrue = iBaseBlacklistIpsService.findByIp(lastIp);
        if (isTrue) {
            return AjaxResult.error(-1, "账号存在违规行为，请联系客服！");
        }
        if (StringUtils.isEmpty(phone)) {
            return AjaxResult.error(-1, "手机号码不能为空");
        }
        if (StringUtils.isEmpty(password)) {
            return AjaxResult.error(-1, "密码不能为空");
        }
        if (StringUtils.isEmpty(username)) {
            return AjaxResult.error(-1, "用户昵称不能为空");
        }
        return registCommonInVersion1(phone, password, username, null, equipmentId, headUrl, invitationCode, lastIp);
    }

    @Autowired
    private IAppUserWhitelistService iAppUserWhitelistService;

    @PostMapping("v1/userLogin")
    @ApiOperation("Version1：用户登录")
    public AjaxResult loginInVersion1(@ApiParam("手机号码") @RequestParam String phone, @ApiParam("密码（需要MD5）") @RequestParam String password, @ApiParam("格式为：设备id,设备名称") String equipmentId, HttpServletRequest request) {
        String lastIp = RequestUtil.getIpAddrByRequest(request);
        // 判断是否为黑名单数据
        Boolean isTrue = iBaseBlacklistIpsService.findByIp(lastIp);
        if (isTrue) {
            return AjaxResult.error(-1, "账号存在违规行为，请联系客服！");
        }
        if (StringUtils.isEmpty(phone)) {
            return AjaxResult.error(-1, "手机号码不能为空！");
        }
        if (StringUtils.isEmpty(password)) {
            return AjaxResult.error(-1, "密码不能为空！");
        }
        int count = userService.countByMobile(phone);
        if (0 == count) {
            return AjaxResult.error(-1, "账号不存在！");
        }
        AppUser userEntity = userService.getOneByMobileAndPassword(phone, password);
        if (null == userEntity) {
            return AjaxResult.error(-1, "用户账号或密码错误");
        } else if (userEntity.getState() == 2) {
            // 用户已存在且账号被删除的情况下，修改账号状态，解禁云信账户
            return AjaxResult.error(-1, "账号异常，请重新注册！");
        }
        if (userEntity.getState() == 1) {
            return AjaxResult.error(-1, "用户已被冻结，请联系管理员或客服！");
        }

        AppUserWhitelist whitelist = new AppUserWhitelist();
        whitelist.setUserId(userEntity.getUserId());
        List<AppUserWhitelist> whitelists = iAppUserWhitelistService.selectAppUserWhitelistList(whitelist);
        if (whitelists.size() > 0) {
            whitelist.setWhitelistIp(lastIp);
            List<AppUserWhitelist> appUserWhitelists = iAppUserWhitelistService.selectAppUserWhitelistList(whitelist);
            if (appUserWhitelists.size() == 0) {
                return AjaxResult.error(-1, "当前IP异常，请确认后重新登陆");
            }
        }
        /*
         * 获取用户设备信息，若无记录则新增
         * 若查询到记录，查看用户此设备状态
         */
        if (StringUtils.isNotBlank(equipmentId)) {
            String[] equipmentInfo = equipmentId.split(",");
            AppUserEquipment userEquipment = iAppUserEquipmentService.getOneByEquipmentId(equipmentInfo[1]);
            Date nowTime = new Date();
            if (null == userEquipment) {
                userEquipment = new AppUserEquipment();
                userEquipment.setCrtTime(nowTime);
                userEquipment.setUserId(userEntity.getUserId());
                userEquipment.setEquipmentId(equipmentId);
                if (equipmentInfo.length > 1) {
                    userEquipment.setEquipmentId(equipmentInfo[1]);
                    userEquipment.setEquipmentName(equipmentInfo[0]);
                }

                userEquipment.setLastLoginTime(nowTime);
                userEquipment.setStatus(0);
                iAppUserEquipmentService.insertAppUserEquipment(userEquipment);
            } else {
                if (1 == userEquipment.getStatus()) {
                    return AjaxResult.error(-1, "用户设备已被禁止，请联系管理员或客服！");
                }
                userEquipment.setUserId(userEntity.getUserId());
                userEquipment.setLastLoginTime(nowTime);
                iAppUserEquipmentService.updateById(userEquipment);
            }
        }

        userEntity.setLastLoginTime(new Date());
        userEntity.setLastIp(lastIp);
        userService.updateAppUser(userEntity);
        String token = loginService.login2(userEntity);
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("expire", expireTime * MILLIS_MINUTE);
        map.put("account", userEntity.getAccount());
        map.put("phone", userEntity.getMobile());
        map.put("userId", userEntity.getUserId());
        map.put("userSig", tencentCloudImUtil.genUserSig(userEntity.getAccount() + "", 86400 * 7));
        map.put("hasLot", userEntity.getHasLot());
        map.put("isRemove", "0");
        map.put("hasPayPass", StringUtils.isBlank(userEntity.getPayPass()) ? "0" : "1");
        return AjaxResult.ok(0, "", map);
    }


    @PostMapping("v1/modifyPassword")
    @ApiOperation("Version1：修改密码")
    public AjaxResult modifyPassword(@ApiParam("原密码（需要MD5）") @RequestParam String oldPassword, @ApiParam("新密码（需要MD5）") @RequestParam String newPassword) {
        AppUser userEntity = userService.getById(getUserId());
        if (!userEntity.getPassword().equals(oldPassword)) return AjaxResult.error(-1, "原密码填写错误！");

        AppUser userRecord = new AppUser();
        // userRecord.setUserId(userEntity.getUserId());
        userRecord.setPassword(newPassword);

        userService.update(userRecord, new QueryWrapper<AppUser>().eq("user_id", userEntity.getUserId()));
        return AjaxResult.ok(0, "", null);
    }

    private AjaxResult registCommonInVersion1(String phone, String password, String username, Long ditchUserId, String equipmentId, String headUrl, String invitationCode, String lastIp) {
        // Start >>>>>>>> 添加到默认群组里 <<<<<<<<<
        AppFunctionConfiguration functionConfiguration = appFunctionConfigurationService.selectAppFunctionConfigurationById(10001L);
        BaseInvitationCode invitationCodeInfo = iBaseInvitationCodeService.getOne(new QueryWrapper<BaseInvitationCode>().eq("invitation_code", invitationCode));
        if (functionConfiguration.getInvitationCodeState() == 0 && invitationCodeInfo == null) {
            return AjaxResult.error(-1, "邀请码不存在！");
        }
        AppUser userRecord = userService.getOneByMobile(phone);
        if (null != userRecord) {
            if (2 == userRecord.getState()) {
                // 用户已存在且账号被删除的情况下，修改账号状态，解禁云信账户
                //                return userService.unBlockUser(userRecord);
            }
            return AjaxResult.error(-1, "账号已存在！");
        }
        Date nowTime = new Date();
        /*
         * 保存用户基本信息
         */
        AppUser user = new AppUser();
        Boolean isShow = true;
        String account = "";
        while (isShow) {
            String num = CommonUtils.get8LengthId(1);
            Integer isAccount = userService.findByAccount(num);
            if (isAccount == 0) {
                account = num;
                isShow = false;
            }
        }
        user.setIsadd(1L);
        user.setHeadImg(headUrl);
        user.setUserId(Long.parseLong(account));
        user.setCreateTime(nowTime);
        user.setAccount(account);
        user.setUsername(username);
        user.setMobile(phone);
        user.setInvitationCode(invitationCode);
        user.setPassword(password);
        user.setLastIp(lastIp);
        user.setSex(0);
        userService.insertAppUser(user);
        // Start >>>>>>>> 账号加入腾讯云 IM <<<<<<<<<
        tencentCloudImUtil.accountImport(account + "", user.getUsername(), user.getHeadImg());
        // End >>>>>>>> 账号加入腾讯云 IM <<<<<<<<<

        if (invitationCodeInfo != null && StringUtils.isNotEmpty(invitationCodeInfo.getDefaultUser())) {
//            String userIds = invitationCodeInfo.getDefaultUser();
//            String[] userid = userIds.split(",");
//            for (int i = 0; userid != null && i < userid.length; i++) {
//                // 添加渠道好友
//                tencentCloudImUtil.FRIEND_ADD(account, userid[i]);
//                // 发送打招呼信息
//                tencentCloudImUtil.sendmsg(userid[i], account, invitationCodeInfo.getSayText());
//            }
            String[] userids = invitationCodeInfo.getDefaultUser().split(",");
            String userId = invitationCodeInfo.getNextOne();
            if (StringUtils.isNotEmpty(userId)) {
                // 添加渠道好友
                tencentCloudImUtil.FRIEND_ADD(account, userId);
                // 发送打招呼信息
                tencentCloudImUtil.sendmsg(userId, account, invitationCodeInfo.getSayText());
                // 跟进下一个
                int index = ArrayUtils.indexOf(userids, userId);
                if (index == userids.length - 1) {
                    invitationCodeInfo.setNextOne(userids[0]);
                } else {
                    invitationCodeInfo.setNextOne(userids[index + 1]);
                }
                iBaseInvitationCodeService.updateById(invitationCodeInfo);
            }

        }
        // End >>>>>>>> 添加到默认群组里 <<<<<<<<<

        // Start >>>>>>>> 添加到默认群组里 <<<<<<<<<
        List<AppGroupInfo> list = iAppGroupInfoService.list(new QueryWrapper<AppGroupInfo>().eq("is_default", 0));
        List<Map<String, Object>> MemberLists = Lists.newArrayList();
        Map<String, Object> map_user = new HashMap<>();
        map_user.put("Member_Account", account);
        MemberLists.add(map_user);

        for (AppGroupInfo info : list) {
            tencentCloudImUtil.groupsAddUsers(MemberLists, info.getGroupId(), info.getGreetingContext());
//            tencentCloudImUtil.sendGroupMsg("欢迎" + user.getUsername() + "加入", info.getGroupId());
        }
        // End >>>>>>>> 添加到默认群组里 <<<<<<<<<

        // Start >>>>>>>> 添加默认好友 <<<<<<<<<
        List<BaseFriendsDefault> friendsDefaults = baseFriendsDefaultService.list();
        for (BaseFriendsDefault friendsDefault : friendsDefaults) {
            tencentCloudImUtil.FRIEND_ADD(account, friendsDefault.getAccount());
            // 发送打招呼信息
            tencentCloudImUtil.sendmsg(friendsDefault.getAccount(), account, friendsDefault.getSayText());
        }
        // End >>>>>>>> 添加到默认群组里 <<<<<<<<< 添加到默认群组里

        // 注册时若存在设备id保存用户设备登录信息
        if (StringUtils.isNotBlank(equipmentId)) {
            String[] equipmentInfo = equipmentId.split(",");
            String equipmentName = equipmentInfo[0];
            if (StringUtils.isNotEmpty(equipmentName)) {
                AppUser appUser2 = new AppUser();
                if (equipmentName.indexOf("iPod") != -1) {
                    appUser2.setEquipment("ios");
                } else if (equipmentName.indexOf("iPhone") != -1) {
                    appUser2.setEquipment("ios");
                } else if (equipmentName.indexOf("iPad") != -1) {
                    appUser2.setEquipment("ios");
                } else if (equipmentName.indexOf("Unknown") != -1) {
                    appUser2.setEquipment("ios");
                } else if (equipmentName.indexOf("Web") != -1) {
                    appUser2.setEquipment("web");
                } else {
                    appUser2.setEquipment("android");
                }
                appUser2.setLastLoginTime(new Date());
                userService.update(appUser2, new QueryWrapper<AppUser>().eq("user_id", user.getUserId()));
            }
            AppUserEquipment userEquipment = iAppUserEquipmentService.getOneByEquipmentId(equipmentInfo[1]);
            if (null == userEquipment) {
                userEquipment = new AppUserEquipment();
                userEquipment.setCrtTime(nowTime);
                userEquipment.setUserId(user.getUserId());
                userEquipment.setEquipmentId(equipmentInfo[0]);
                if (equipmentInfo.length > 1) {
                    userEquipment.setEquipmentId(equipmentInfo[1]);
                    userEquipment.setEquipmentName(equipmentInfo[0]);
                }
                userEquipment.setLastLoginTime(nowTime);
                userEquipment.setStatus(0);
                iAppUserEquipmentService.save(userEquipment);
            } else {
                if (1 == userEquipment.getStatus()) {
                    return AjaxResult.error(-10001, "用户设备已被禁止，请联系管理员或客服！");
                }
                userEquipment.setUserId(user.getUserId());
                userEquipment.setLastLoginTime(nowTime);
                iAppUserEquipmentService.updateById(userEquipment);
            }
        }

        Map<String, Object> map = new HashMap<>();
        map.put("userId", user.getUserId());
        map.put("account", user.getAccount());
        map.put("userSig", tencentCloudImUtil.genUserSig(user.getAccount() + "", 86400 * 7));
        map.put("hasLot", user.getHasLot());
        map.put("isRemove", "0");
        map.put("hasPayPass", "0");
        String token = loginService.login2(user);
        map.put("token", token);
        return AjaxResult.ok(0, "", map);
    }

}
